package cn.seaboot.admin.mvc.response;

import cn.seaboot.admin.mvc.Result;
import cn.seaboot.admin.mvc.mask.Desensitize;
import cn.seaboot.admin.mvc.mask.ReturnValueDesensitization;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 数据脱敏
 * <p>
 * 仅作为代码样例展示，使用的时候，注册当前类
 *
 * <pre>
 * - @ControllerAdvice(basePackages = "cn.seaboot")
 * </pre>
 *
 * @author Created by Mr.css on 2018-05-11.
 * @version 2018-05-11.
 */
public class ControllerDesensitizationExample implements ResponseBodyAdvice<Object> {

    /**
     * 数据脱敏
     */
    @Resource
    private ReturnValueDesensitization returnValueDesensitization;

    /**
     * 包含脱敏注解，则对返回值增加脱敏
     *
     * @param methodParameter the return type
     * @param aClass          the selected converter type
     * @return {@code true} if {@link #beforeBodyWrite} should be invoked;
     * {@code false} otherwise
     */
    @Override
    public boolean supports(@NotNull MethodParameter methodParameter,
                            @NotNull Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(Desensitize.class);
    }

    @Override
    public Object beforeBodyWrite(Object o
            , @NotNull MethodParameter methodParameter
            , @NotNull MediaType mediaType
            , @NotNull Class<? extends HttpMessageConverter<?>> aClass
            , @NotNull ServerHttpRequest serverHttpRequest
            , @NotNull ServerHttpResponse serverHttpResponse) {
        returnValueDesensitization.process(o);
        return Result.succeed(o);
    }
}
